package cn.bdqn.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import cn.bdqn.tools.ConfigManager;

/**
 * 鎿嶄綔鏁版嵁搴撶殑鍩虹被鈥斺�闈欐�绫�
 *
 */
public class BaseDao {
	
	
	/**
	 * 鑾峰彇杩炴帴瀵硅薄
	 * @return
	 */
	public static Connection getConnection(){
		//鍒涘缓Connection瀵硅薄
		Connection conn = null;
		String driver = ConfigManager.getInstance().getValue("driver");
		String url = ConfigManager.getInstance().getValue("url");
		String user = ConfigManager.getInstance().getValue("user");
		String password = ConfigManager.getInstance().getValue("password");
		try {
			Class.forName(driver);
			conn=DriverManager.getConnection(url, user, password);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}
	
	/**
	 * 鍏抽棴鏁版嵁搴�
	 * @param conn 杩炴帴瀵硅薄
	 * @param stmt Statement瀵硅薄
	 * @param rs 缁撴灉闆嗗璞�
	 */
	public void closeAll(Connection conn,Statement stmt,ResultSet rs){
		//鍒ゆ柇缁撴灉闆嗘槸鍚︿负绌�
		if(rs != null){
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		//鍒ゆ柇Statement鏄惁涓虹┖
		if(stmt != null){
			try {
				stmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}		
		//鍒ゆ柇杩炴帴瀵硅薄鏄惁涓虹┖
		if(conn != null){
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 澧炪�鍒犮�鏀规搷浣�
	 * @param sql sql璇彞
	 * @param params 鍙傛暟鏁扮粍
	 * @return  鍙楀奖鍝嶈鏁�
	 */
	protected int executeUpdate(String sql,Object[] params){
		//鍒涘缓PreparedStatement瀵硅薄
		PreparedStatement pstmt = null;
		//瀹氫箟涓�釜鍙橀噺
		int num = 0;
		//杩炴帴鏁版嵁搴�
		Connection conn = getConnection();
		//寮傚父澶勭悊
		try {
			pstmt = conn.prepareStatement(sql);
			if(params != null){
				//寰幆
				for(int i = 0; i < params.length; i++){
					//缂栧啓sql璇彞
					pstmt.setObject(i+1, params[i]);
				}
			}
			num = pstmt.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			closeAll(conn,pstmt,null);
		}
		return num;
	}
}
